/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <fastdds/dds/subscriber/Subscriber.hpp>
#include <fastdds/dds/subscriber/DataReader.hpp>

#include "dal_fastdds/dbh/DalDbhReliableReader.hpp"

DalDbhReliableReader::DalDbhReliableReader() {}

DalDbhReliableReader::~DalDbhReliableReader() {}

bool DalDbhReliableReader::CreateDbhRecvNotifyWriter()
{
    DataWriterQos f_qos;
    f_qos.reliability().kind = RELIABLE_RELIABILITY_QOS;
    f_qos.history().kind = KEEP_ALL_HISTORY_QOS;
    f_qos.history().depth = 5;
    f_qos.durability().kind = VOLATILE_DURABILITY_QOS;

#ifdef DAL_FASTDDS_DATA_SHARING_DISABLED
    f_qos.data_sharing().off();
#endif

    dbh_recv_notify_publisher_ = fastdds_participant_->create_publisher(PUBLISHER_QOS_DEFAULT);
    dbh_recv_notify_writer_ = dbh_recv_notify_publisher_->create_datawriter(
        dbh_recv_notify_topic_, f_qos, nullptr, StatusMask::all());
    if (dbh_recv_notify_writer_)
        return true;
    return false;
}

bool DalDbhReliableReader::CreateDbhSendNotifyReader()
{
    DataReaderQos f_qos;
    f_qos.reliability().kind = RELIABLE_RELIABILITY_QOS;
    f_qos.history().kind = KEEP_ALL_HISTORY_QOS;
    f_qos.history().depth = 5;
    f_qos.durability().kind = VOLATILE_DURABILITY_QOS;

#ifdef DAL_FASTDDS_DATA_SHARING_DISABLED
    f_qos.data_sharing().off();
#endif

    dbh_send_notify_reader_ = fastdds_sub_->create_datareader(dbh_send_notify_topic_,
                                                              f_qos,
                                                              dbh_send_notify_reader_listener_,
                                                              dbh_send_notify_reader_status_mask_);
    if (dbh_send_notify_reader_) {
        return true;
    }
    return false;
}

void DalDbhReliableReader::SetDbhRecvNotifyMsg()
{
    memcpy(dbh_recv_notify_msg_.uuid.data(), dbh_send_notify_msg_.uuid.data(), UUID_LEN);
}

bool DalDbhReliableReader::SendDbhRecvNotifyMsg()
{
    InstanceHandle_t f_handle;
    dal_fastrtps_shared_cpp::SerializedData sdata;
    sdata.is_cdr_buffer = false;
    sdata.data = static_cast<void*>(&dbh_recv_notify_msg_);
    sdata.impl = dbh_recv_notify_msg_ts_callbacks_;
    if (DAL_RETCODE_OK != dbh_recv_notify_writer_->write(&sdata, f_handle)) {
        return false;
    }
    return true;
}